<template>
  <div>
    <div
      style="
        display: flex;
        justify-content: space-between;
        width: 100%;
        padding: 24px 16px 0 12px;
      "
    >
      <el-form inline>
        <el-form-item label="起始日期（含）">
          <el-date-picker
            style="width: 150px"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-model="formData.begin"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期（不含）">
          <el-date-picker
            style="width: 150px"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            v-model="formData.end"
          ></el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="科室">
          <el-select v-model="formData.orgid" style="width: 150px">
            <el-option label="一室" :value="12"></el-option>
            <el-option label="二室" :value="13"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <el-form inline>
        <el-form-item>
          <el-button type="primary" @click="main()">统计</el-button>
          <el-button type="success" @click="exportExcel()" :disabled="!showPre"
            >导出</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 12px 16px 24px 12px">
      <el-tag
        type="info"
        style="display: inline-block; width: 100%; height: auto"
      >
        <div style="display: flex; align-items: center; padding: 0 8px">
          <div style="font-size: 60px">
            <InfoFilled style="width: 60px; height: 60px" />
          </div>
          <div style="padding: 12px">
            <div style="padding: 4px">
              带培时间为0小时的人员不论是否为教员均不统计在内
            </div>
            <div style="padding: 4px">
              教员独立上岗或带培小时数均不记入OMA/SUP席位时间
            </div>
            <div style="padding: 4px">
              学员见习小时数统计包含所有席位（如OMA）的见习小时数
            </div>
          </div>
        </div>
      </el-tag>
    </div>
    <transition name="el-fade-in">
      <div v-if="showPre" style="width: 100%">
        <el-tabs type="border-card">
          <el-tab-pane label="学员小时统计">
            <el-table
              :data="tableData.trainee"
              style="width: 100%"
              :row-style="averageRowStyle"
            >
              <el-table-column
                prop="name"
                label="姓名"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="totalEC"
                label="管制席"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="totalPLC"
                label="协调席"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="total"
                label="合计"
                min-width="82px"
                :resizable="false"
                align="center"
              />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="教员小时统计"
            ><el-table
              :data="tableData.coach"
              style="width: 100%"
              :row-style="averageRowStyle"
            >
              <el-table-column
                prop="name"
                label="姓名"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="trainingEC"
                label="管制带培"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="trainingPLC"
                label="协调带培"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="training"
                label="合计带培"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="standaloneEC"
                label="管制独立"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="standalonePLC"
                label="协调独立"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="standalone"
                label="合计独立"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="totalEC"
                label="管制席"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="totalPLC"
                label="协调席"
                min-width="82px"
                :resizable="false"
                align="center"
              />
              <el-table-column
                prop="total"
                label="合计"
                min-width="82px"
                :resizable="false"
                align="center"
              /> </el-table
          ></el-tab-pane>
          <el-tab-pane label="原始数据">
            <table style="width: 100%">
              <tr class="tr-line">
                <th style="width: 60px">#</th>
                <th style="width: 80px">姓名</th>
                <th style="width: 60px">扇区</th>
                <th style="width: 120px">岗位</th>
                <th style="width: 60px">角色</th>
                <th style="width: 180px">开始时间</th>
                <th style="width: 180px">结束时间</th>
                <th style="width: 80px">小时数</th>
              </tr>
              <tr v-for="(cell, idx) in tableData.raw" class="tr-line">
                <th style="width: 60px">{{ idx }}</th>
                <td style="width: 80px">{{ cell.name }}</td>
                <td style="width: 60px">{{ cell.sector }}</td>
                <td style="width: 120px">{{ cell.post }}</td>
                <td style="width: 60px">{{ cell.role }}</td>
                <td style="width: 180px">{{ cell.begin }}</td>
                <td style="width: 180px">{{ cell.end }}</td>
                <td style="width: 80px">{{ cell.hours }}</td>
              </tr>
            </table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </transition>
    <transition name="el-fade-in">
      <div
        v-if="loading"
        style="
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 10;
        "
        v-loading="loading"
      ></div>
    </transition>
    <AlertView v-if="showAlert" />
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import axios from "axios";
import dayjs from "dayjs";
import * as XLSX from "xlsx";
import AlertView from "@/components/Alert/index.vue";
import useSeatStore from "@/store/seat.js";

const seatStore = useSeatStore();
const showAlert = computed(() => !seatStore.isServiceAvailable);

const showPre = ref(false);
const loading = ref(false);
const tableData = ref({ trainee: [], coach: [] });

const formData = ref({
  begin: dayjs().subtract(1, "month").format("YYYY-MM") + "-21",
  end: dayjs().format("YYYY-MM") + "-21",
  orgid: 13,
});

const source = {
  data: new Array(),
};

const result = {
  trainee: {},
  coach: {},
};

import getSeatHours from "./getSeatHours.js";
const main = () => {
  reset();
  let start = dayjs(formData.value.begin).format("YYYY-MM-DD");
  let end = dayjs(formData.value.end).format("YYYY-MM-DD");
  getSeatHours(start, end).then((data) => {
    doSummary(data);
    afterQuery();
  });
  // let url = `api/hours_personal_report_get.php?start=${start}&end=${end}`;
  // console.log(url);
  // axios
  //   .get(url)
  //   .then((response) => {
  //     console.log(response.data);
  //     // source.data = response.data.data;
  //     doSummary(response.data.data);
  //     afterQuery();
  //   })
  //   .catch((error) => {
  //     console.error(error);
  //   });
};

const reset = () => {
  showPre.value = false;
  loading.value = true;
  source.data = new Array();
  source.received = 0;
  result.trainee = {
    average: {
      total: 0,
      totalEC: 0,
      totalPLC: 0,
    },
    details: {},
  };
  result.coach = {
    average: {
      total: 0,
      totalEC: 0,
      totalPLC: 0,
      standalone: 0,
      standaloneEC: 0,
      standalonePLC: 0,
      training: 0,
      trainingEC: 0,
      trainingPLC: 0,
    },
    details: {},
  };
};

const averageRowStyle = ({ row, rowIndex }) => {
  if (rowIndex == 0) {
    return { fontWeight: "bold", backgroundColor: "rgba(128,128,128,0.15)" };
  } else {
    return {};
  }
};

const fetchTableData = () => {
  let trainee = new Array();
  let coach = new Array();

  for (let name in result.trainee.details) {
    let guy = JSON.parse(JSON.stringify(result.trainee.details[name]));
    for (let attr in guy) {
      guy[attr] = guy[attr].toFixed(1);
    }
    guy["name"] = name;
    trainee.push(guy);
  }
  for (let name in result.coach.details) {
    let guy = JSON.parse(JSON.stringify(result.coach.details[name]));
    for (let attr in guy) {
      guy[attr] = guy[attr].toFixed(1);
    }
    guy["name"] = name;
    coach.push(guy);
  }

  let traineeAvg = JSON.parse(JSON.stringify(result.trainee.average));
  for (let attr in traineeAvg) {
    traineeAvg[attr] = traineeAvg[attr].toFixed(1);
  }
  traineeAvg["name"] = "平均值";
  trainee.unshift(traineeAvg);

  let coachAvg = JSON.parse(JSON.stringify(result.coach.average));
  console.log("TrainingSummary", "fetchTableData", "coachAvg", coachAvg);
  for (let attr in coachAvg) {
    coachAvg[attr] = coachAvg[attr] ? coachAvg[attr].toFixed(1) : 0;
  }
  coachAvg["name"] = "平均值";
  coach.unshift(coachAvg);

  return {
    coach,
    trainee,
    raw: source.data,
  };
};

const createWs = (data, fields, titles) => {
  const ws = XLSX.utils.json_to_sheet(data, {
    header: fields,
  });
  const range = XLSX.utils.decode_range(ws["!ref"]);
  for (let c = range.s.c; c <= range.e.c; c++) {
    const header = XLSX.utils.encode_col(c) + "1";
    ws[header].v = titles[ws[header].v];
  }
  return ws;
};

const exportExcel = () => {
  let wsTrainee = createWs(
    tableData.value.trainee,
    ["name", "totalEC", "totalPLC", "total"],
    { name: "姓名", total: "合计", totalEC: "管制", totalPLC: "协调" }
  );
  let wsCoach = createWs(
    tableData.value.coach,
    [
      "name",
      "trainingEC",
      "trainingPLC",
      "training",
      "standaloneEC",
      "standalonePLC",
      "standalone",
      "totalEC",
      "totalPLC",
      "total",
    ],
    {
      name: "姓名",
      total: "合计",
      totalEC: "管制",
      totalPLC: "协调",
      training: "带培合计",
      trainingEC: "管制带培",
      trainingPLC: "协调带培",
      standalone: "独立合计",
      standaloneEC: "独立管制",
      standalonePLC: "独立协调",
    }
  );
  let wsRaw = createWs(
    tableData.value.raw,
    ["name", "sector", "post", "role", "begin", "end", "hours"],
    {
      name: "姓名",
      sector: "扇区",
      post: "岗位",
      role: "角色",
      begin: "开始时间",
      end: "结束时间",
      hours: "小时数",
    }
  );
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, wsTrainee, "学员小时统计");
  XLSX.utils.book_append_sheet(wb, wsCoach, "教员小时统计");
  XLSX.utils.book_append_sheet(wb, wsRaw, "原始数据");
  const fileName =
    `CDTCC-2KT教学员小时统计（${formData.value.begin}至${formData.value.end}）@` +
    dayjs().format("YYYY_MM_DD_HH_mm_ss");
  XLSX.writeFile(wb, fileName + ".xlsx");
};
const computeAverage = () => {
  for (let name in result.coach.details) {
    let guy = result.coach.details[name];
    if (guy.training == 0) {
      result.coach.average.total -= guy.total;
      result.coach.average.totalEC -= guy.totalEC;
      result.coach.average.totalPLC -= guy.totalPLC;
      result.coach.average.standalone -= guy.standalone;
      result.coach.average.standaloneEC -= guy.standaloneEC;
      result.coach.average.standalonePLC -= guy.standalonePLC;
      delete result.coach.details[name];
    }
  }
  let coachCount = Object.keys(result.coach.details).length;
  result.coach.average.total /= coachCount;
  result.coach.average.totalEC /= coachCount;
  result.coach.average.totalPLC /= coachCount;
  result.coach.average.standalone /= coachCount;
  result.coach.average.standaloneEC /= coachCount;
  result.coach.average.standalonePLC /= coachCount;
  result.coach.average.training /= coachCount;
  result.coach.average.trainingEC /= coachCount;
  result.coach.average.trainingPLC /= coachCount;
  let traineeCount = Object.keys(result.trainee.details).length;
  result.trainee.average.total /= traineeCount;
  result.trainee.average.totalEC /= traineeCount;
  result.trainee.average.totalPLC /= traineeCount;
};

const afterQuery = async () => {
  computeAverage();
  tableData.value = fetchTableData();
  console.log(
    "TrainingSummary",
    "afterQuery",
    "result:",
    result,
    "tableData:",
    tableData.value
  );
  await nextTick();
  showPre.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

const doSummary = (data) => {
  // let begin = dayjs(formData.value.begin);
  // let end = dayjs(formData.value.end);
  for (let i = 0; i < data.length; i++) {
    let cell = data[i];
    // if (begin.diff(cell.begin) > 0) {
    //   continue;
    // }
    // if (end.diff(cell.end) <= 0) {
    //   continue;
    // }
    let hours = cell.hours == null ? 0 : cell.hours;
    // let hours = cell.hours == null ? dayjs().diff(cell.begin, "hour", true) : cell.hours;
    source.data.push(cell);
    if (cell.role == "学员") {
      // 新建学员
      if (!result.trainee.details[cell.name]) {
        result.trainee.details[cell.name] = {
          total: 0,
          totalEC: 0,
          totalPLC: 0,
        };
      }
      // 见习总
      result.trainee.average.total += hours;
      result.trainee.details[cell.name].total += hours;
      if (cell.post == "管制岗") {
        // 见习管制
        result.trainee.average.totalEC += hours;
        result.trainee.details[cell.name].totalEC += hours;
      } else {
        // 见习协调
        result.trainee.average.totalPLC += hours;
        result.trainee.details[cell.name].totalPLC += hours;
      }
    } else if (cell.sector.includes("TM")) {
      // 新建教员
      if (!result.coach.details[cell.name]) {
        result.coach.details[cell.name] = {
          total: 0,
          totalEC: 0,
          totalPLC: 0,
          standalone: 0,
          standaloneEC: 0,
          standalonePLC: 0,
          training: 0,
          trainingEC: 0,
          trainingPLC: 0,
        };
      }
      // 总时间
      result.coach.average.total += hours;
      result.coach.details[cell.name].total += hours;
      if (cell.role == "教员") {
        // 带培总
        result.coach.average.training += hours;
        result.coach.details[cell.name].training += hours;
        if (cell.post == "管制岗") {
          // 带培管制
          result.coach.average.trainingEC += hours;
          result.coach.details[cell.name].trainingEC += hours;
          result.coach.average.totalEC += hours;
          result.coach.details[cell.name].totalEC += hours;
        } else {
          // 带培协调
          result.coach.average.trainingPLC += hours;
          result.coach.details[cell.name].trainingPLC += hours;
          result.coach.average.totalPLC += hours;
          result.coach.details[cell.name].totalPLC += hours;
        }
      } else {
        // 独立总
        result.coach.average.standalone += hours;
        result.coach.details[cell.name].standalone += hours;
        if (cell.post == "管制岗") {
          // 独立管制
          result.coach.average.standaloneEC += hours;
          result.coach.details[cell.name].standaloneEC += hours;
          result.coach.average.totalEC += hours;
          result.coach.details[cell.name].totalEC += hours;
        } else {
          // 独立协调
          result.coach.average.standalonePLC += hours;
          result.coach.details[cell.name].standalonePLC += hours;
          result.coach.average.totalPLC += hours;
          result.coach.details[cell.name].totalPLC += hours;
        }
      }
    }
  }
  console.log("doSummary", result);
};
</script>

<style scoped>
.tr-line {
  width: 100%;
  padding: 8px;
  font-size: 14px;
  display: flex;
  justify-content: space-around;
  text-align: center;
  border-bottom: 1px solid rgba(128, 128, 128, 0.25);
  cursor: pointer;
  transition: all 0.5 ease-in-out;
}
.tr-line:hover {
  background-color: rgba(128, 128, 128, 0.15);
}
</style>
